import { useNavigation } from '@react-navigation/native';
import { useEffect, useMemo, useState } from 'react';
import { Platform } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import {
  JSExceptionHandler,
  NativeExceptionHandler,
  setJSExceptionHandler,
  setNativeExceptionHandler,
} from 'react-native-exception-handler';
import { useSelector } from 'react-redux';

import dayjs from 'dayjs';

import { APP_NAME } from '@/constants';
import { RootState } from '@/stores/store';
import { isShowTestURL } from '@/utils/http';
const generateContent = (title: string, content: unknown) => {
  return [{ tag: 'text', text: `${title}: ${JSON.stringify(content)}` }];
};
export const useExceptionHandler = () => {
  const navigation = useNavigation();
  const userID = useSelector((state: RootState) => state.user.userId);
  const appName = APP_NAME;
  const webHookUrl = 'https://open.feishu.cn/open-apis/bot/v2/hook/e44a46f6-9387-4daa-a09f-6dab87dd54c5';
  const [isEmulator, setIsEmulator] = useState<boolean>(false);
  const info = useMemo(() => {
    // 获取手机型号 (iPhone 13 Pro Max)
    const model = DeviceInfo.getModel();
    // 获取系统版本号 (13.3)
    const systemVersion = DeviceInfo.getSystemVersion();
    // 获取当前环境 TODO: 根据应用自行判断
    const environment = isShowTestURL ? 'Development' : 'Production';
    return [
      generateContent('platform', Platform.OS),
      generateContent('version', DeviceInfo.getVersion()),
      generateContent('Phone model', model),
      generateContent('System Version', systemVersion),
      generateContent('environment', environment),
      generateContent('Time', dayjs().format('YYYY-MM-DD HH:mm:ss')),
      generateContent('UserId', userID || 'None'),
      generateContent('isEmulator', isEmulator),
    ];
  }, [isShowTestURL, userID, isEmulator]);

  useEffect(() => {
    DeviceInfo.isEmulator().then(setIsEmulator);
  }, []);

  useEffect(() => {
    // TODO: 开发环境下不进行异常捕获
    if (__DEV__) {
      return;
    }

    //是否在开发模式下替代红屏，默认为 false
    const allowInDevMode = true;
    // Android特定参数，应用程序是否在发生错误时强制退出
    const forceAppQuit = false;
    // 是否有其他崩溃分析模块
    const executeDefaultHandler = true;

    const exceptionHandler: JSExceptionHandler = (error, isFatal) => {
      fetch(webHookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          msg_type: 'post',
          content: {
            post: {
              'zh-CN': {
                title: appName,
                content: [
                  ...info,
                  generateContent('error type', 'JS'),
                  generateContent('is fatal', isFatal ? 'yes' : 'no'),
                  generateContent('message', error),
                  generateContent('navigation state', navigation.getState()),
                ],
              },
            },
          },
        }),
      }).catch((err) => {
        console.error(err);
      });
    };

    setJSExceptionHandler(exceptionHandler, allowInDevMode);

    const nativeExceptionHandler: NativeExceptionHandler = (exceptionString) => {
      // your exception handler code here
      fetch(webHookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          msg_type: 'post',
          content: {
            post: {
              'en-US': {
                title: appName,
                content: [
                  ...info,
                  generateContent('error type', 'Native'),
                  generateContent('navigation state', navigation.getState()),
                  generateContent('message', exceptionString),
                ],
              },
            },
          },
        }),
      }).catch((error) => {
        console.error(error);
      });
    };
    setNativeExceptionHandler(nativeExceptionHandler, forceAppQuit, executeDefaultHandler);
  }, [info]);
};
